#define  _CRT_SECURE_NO_WARNINGS 1
#include "list.h"

ListNode* BuyListNode(LTNodeType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

ListNode* ListNodeInit()
{
	ListNode* pn = BuyListNode(0);
	pn->next = pn;
	pn->prev = pn;
	return pn;
}

void ListNodePrint(ListNode* phead)
{
	assert(phead);

	ListNode* curr = phead->next;
	while (curr != phead)
	{
		printf("%d ", curr->data);
		curr = curr->next;
	}
	printf("\n");
}

void ListNodeInsert(ListNode* pos, LTNodeType x)
{
	assert(pos);

	ListNode* prev = pos->prev;
	ListNode* newnode = BuyListNode(x);

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;

}

void ListNodeErase(ListNode* phead, ListNode* pos)
{
	assert(pos);
	assert(phead != pos);

	ListNode* prev = pos->prev;
	ListNode* next = pos->next;

	prev->next = next;
	next->prev = prev;

	free(pos);
	pos = NULL;
}

void ListNodePushFront(ListNode* phead, LTNodeType x)
{
	assert(phead);

	ListNodeInsert(phead->next, x);

}

void ListNodePushBack(ListNode* phead, LTNodeType x)
{
	assert(phead);

	ListNodeInsert(phead, x);
}

void ListNodePopFront(ListNode* phead)
{
	assert(phead);

	ListNodeErase(phead, phead->next);
}

void ListNodePopBack(ListNode* phead)
{
	assert(phead);

	ListNodeErase(phead, phead->prev);

}

ListNode* ListNodeFind(ListNode* phead, LTNodeType x)
{
	assert(phead);

	ListNode* curr = phead->next;
	while (curr != phead)
	{
		if (curr->data == x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}

void ListNodeDestory(ListNode* phead)
{
	assert(phead);

	ListNode* curr = phead->next;
	ListNode* del = NULL;
	while (curr != phead)
	{
		del = curr;
		curr = curr->next;

		free(del);
	}
	free(phead);
	phead = NULL;
}